import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserFavorite } from './entities/user-favorite.entity';
import { UserReadingHistory } from './entities/user-reading-history.entity';
import { Comment } from './entities/comment.entity';
import { Novel } from './entities/novel.entity';
import { Bookshelf, BookshelfStatus } from './entities/bookshelf.entity';

@Injectable()
export class InteractionService {
  constructor(
    @InjectRepository(UserFavorite)
    private favoriteRepository: Repository<UserFavorite>,
    @InjectRepository(UserReadingHistory)
    private readingHistoryRepository: Repository<UserReadingHistory>,
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
    @InjectRepository(Novel)
    private novelRepository: Repository<Novel>,
    @InjectRepository(Bookshelf)
    private bookshelfRepository: Repository<Bookshelf>,
  ) {}

  /**
   * 检查是否已收藏
   */
  async checkFavorite(userId: number, novelId: number): Promise<boolean> {
    const favorite = await this.favoriteRepository.findOne({
      where: { userId, novelId },
    });
    return !!favorite;
  }

  /**
   * 收藏小说
   */
  async addToFavorite(userId: number, novelId: number, bookshelfId?: number): Promise<UserFavorite> {
    // 检查小说是否存在
    const novel = await this.novelRepository.findOne({
      where: { id: novelId },
    });
    if (!novel) {
      throw new NotFoundException('小说不存在');
    }

    // 检查是否已收藏
    const existingFavorite = await this.favoriteRepository.findOne({
      where: { userId, novelId },
    });

    if (existingFavorite) {
      throw new BadRequestException('小说已在收藏列表中');
    }

    // 如果指定了书架，检查书架是否存在且属于当前用户
    if (bookshelfId) {
      const bookshelf = await this.bookshelfRepository.findOne({
        where: { id: bookshelfId, userId, status: BookshelfStatus.ACTIVE },
      });
      if (!bookshelf) {
        throw new NotFoundException('书架不存在或无权限访问');
      }
    } else {
      // 如果没有指定书架，使用用户的默认书架（如果不存在则创建）
      const defaultBookshelf = await this.getOrCreateDefaultBookshelf(userId);
      bookshelfId = defaultBookshelf.id;
    }

    const favorite = new UserFavorite();
    favorite.userId = userId;
    favorite.novelId = novelId;
    favorite.bookshelfId = bookshelfId || null;

    // 更新小说收藏数
    await this.novelRepository.increment({ id: novelId }, 'favoriteCount', 1);

    return this.favoriteRepository.save(favorite);
  }

  /**
   * 取消收藏
   */
  async removeFromFavorite(
    userId: number,
    novelId: number,
  ): Promise<{ success: boolean; message?: string }> {
    try {
      const favorite = await this.favoriteRepository.findOne({
        where: { userId, novelId },
      });

      if (!favorite) {
        return { success: false, message: '收藏记录不存在' };
      }

      await this.favoriteRepository.remove(favorite);

      // 更新小说收藏数
      await this.novelRepository.decrement({ id: novelId }, 'favoriteCount', 1);

      return { success: true };
    } catch (error) {
      return { success: false, message: '删除失败' };
    }
  }

  /**
   * 获取用户收藏列表
   */
  async getUserFavorites(userId: number, options: any = {}) {
    const { page = 1, limit = 10, bookshelfId, sortBy = 'createdAt', sortOrder = 'desc' } = options;
    const skip = (page - 1) * limit;

    const where: any = { userId };
    if (bookshelfId) {
      where.bookshelfId = bookshelfId;
    }

    // 构建排序条件
    const order: any = {};
    if (sortBy === 'novel.title') {
      order['novel'] = { title: sortOrder.toUpperCase() };
    } else if (sortBy === 'novel.readCount') {
      order['novel'] = { readCount: sortOrder.toUpperCase() };
    } else {
      order[sortBy] = sortOrder.toUpperCase();
    }

    const [favorites, total] = await this.favoriteRepository.findAndCount({
      where,
      relations: ['novel', 'novel.masterCategory', 'bookshelf'],
      order,
      take: limit,
      skip,
    });

    return {
      items: favorites,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 添加阅读历史
   */
  async addReadingHistory(
    userId: number,
    data: any,
  ): Promise<UserReadingHistory> {
    const { novelId, chapterId, readProgress } = data;

    // 检查小说是否存在
    const novel = await this.novelRepository.findOne({
      where: { id: novelId },
    });
    if (!novel) {
      throw new NotFoundException('小说不存在');
    }

    // 查找或创建阅读历史
    let history = await this.readingHistoryRepository.findOne({
      where: { userId, novelId },
    });

    if (history) {
      // 更新现有记录
      history.chapterId = chapterId;
      history.readProgress = readProgress;
      history.lastReadAt = new Date();
    } else {
      // 创建新记录
      history = new UserReadingHistory();
      history.userId = userId;
      history.novelId = novelId;
      history.chapterId = chapterId;
      history.readProgress = readProgress;
      history.lastReadAt = new Date();
    }

    return this.readingHistoryRepository.save(history);
  }

  /**
   * 获取用户评论列表
   */
  async getUserComments(userId: number, options: any): Promise<any> {
    const { page = 1, limit = 10 } = options;
    const skip = (page - 1) * limit;

    const [comments, total] = await this.commentRepository.findAndCount({
      where: { userId },
      relations: ['novel', 'novel.masterCategory'],
      order: { createdAt: 'DESC' },
      take: limit,
      skip,
    });

    return {
      items: comments,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 检查是否已收藏
   */
  async isFavorite(userId: number, novelId: number): Promise<boolean> {
    const favorite = await this.favoriteRepository.findOne({
      where: { userId, novelId },
    });
    return !!favorite;
  }

  /**
   * 记录阅读进度
   */
  async updateReadingProgress(
    userId: number,
    novelId: number,
    chapterId: number,
    readPosition: number = 0,
  ): Promise<UserReadingHistory> {
    // 检查小说是否存在
    const novel = await this.novelRepository.findOne({
      where: { id: novelId },
    });
    if (!novel) {
      throw new NotFoundException('小说不存在');
    }

    // 查找或创建阅读历史
    let history = await this.readingHistoryRepository.findOne({
      where: { userId, novelId },
    });

    if (history) {
      // 更新现有记录
      history.chapterId = chapterId;
      history.readPosition = readPosition;
      history.lastReadAt = new Date();

      // 计算阅读进度（简化版本，基于章节位置）
      const totalChapters = await this.getChapterCount(novelId);
      if (totalChapters > 0) {
        const currentChapter = await this.getChapterPosition(
          novelId,
          chapterId,
        );
        history.readProgress = Math.min(
          (currentChapter / totalChapters) * 100,
          100,
        );
      }

      return this.readingHistoryRepository.save(history);
    } else {
      // 创建新记录
      history = new UserReadingHistory();
      history.userId = userId;
      history.novelId = novelId;
      history.chapterId = chapterId;
      history.readPosition = readPosition;
      history.readProgress = 0;
      history.lastReadAt = new Date();

      return this.readingHistoryRepository.save(history);
    }
  }

  /**
   * 获取用户阅读历史
   */
  async getUserReadingHistory(userId: number, options: any = {}) {
    const { page = 1, limit = 10 } = options;
    const skip = (page - 1) * limit;

    const [history, total] = await this.readingHistoryRepository.findAndCount({
      where: { userId },
      relations: ['novel', 'novel.masterCategory', 'chapter'],
      order: { lastReadAt: 'DESC' },
      take: limit,
      skip,
    });

    return {
      items: history,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 获取小说阅读进度
   */
  async getReadingProgress(
    userId: number,
    novelId: number,
  ): Promise<UserReadingHistory | null> {
    return this.readingHistoryRepository.findOne({
      where: { userId, novelId },
      relations: ['chapter'],
    });
  }

  /**
   * 创建评论
   */
  async createComment(
    userId: number,
    data: {
      novelId: number;
      chapterId?: number;
      content: string;
      parentId?: number | null;
    },
  ): Promise<Comment> {
    const { novelId, chapterId, content, parentId } = data;
    // 检查小说是否存在
    const novel = await this.novelRepository.findOne({
      where: { id: novelId },
    });
    if (!novel) {
      throw new NotFoundException('小说不存在');
    }

    // 如果是回复评论，检查父评论是否存在
    if (parentId) {
      const parentComment = await this.commentRepository.findOne({
        where: { id: parentId, novelId },
      });
      if (!parentComment) {
        throw new NotFoundException('父评论不存在');
      }
    }

    const comment = new Comment();
    comment.userId = userId;
    comment.novelId = novelId;
    comment.parentId = parentId || null;
    comment.content = content;
    comment.likeCount = 0;

    return this.commentRepository.save(comment);
  }

  /**
   * 获取小说评论列表
   */
  async getNovelComments(novelId: number, options: any = {}): Promise<any> {
    const { page = 1, limit = 10, sortBy = 'latest' } = options;
    const skip = (page - 1) * limit;

    let order: any = {};
    switch (sortBy) {
      case 'latest':
        order = { createdAt: 'DESC' };
        break;
      case 'oldest':
        order = { createdAt: 'ASC' };
        break;
      case 'popular':
        order = { likeCount: 'DESC' };
        break;
      default:
        order = { createdAt: 'DESC' };
    }

    const [comments, total] = await this.commentRepository.findAndCount({
      where: { novelId, parentId: null as any },
      relations: ['user', 'replies', 'replies.user'],
      order,
      take: limit,
      skip,
    });

    return {
      items: comments,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 点赞评论
   */
  async likeComment(commentId: number): Promise<Comment> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
    });

    if (!comment) {
      throw new NotFoundException('评论不存在');
    }

    comment.likeCount += 1;
    return this.commentRepository.save(comment);
  }

  /**
   * 删除评论
   */
  async deleteComment(userId: number, commentId: number): Promise<void> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId, userId },
    });

    if (!comment) {
      throw new NotFoundException('评论不存在或无权限删除');
    }

    await this.commentRepository.remove(comment);
  }

  /**
   * 获取章节总数
   */
  private async getChapterCount(novelId: number): Promise<number> {
    // 这里需要注入ChapterService，但为了简化，我们返回一个模拟值
    // 在实际项目中，这应该通过ChapterService获取
    return 10;
  }

  /**
   * 获取章节位置
   */
  private async getChapterPosition(
    novelId: number,
    chapterId: number,
  ): Promise<number> {
    // 同样，这是一个简化的实现
    return chapterId;
  }

  /**
   * 取消点赞评论
   */
  async unlikeComment(commentId: number): Promise<Comment> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
    });

    if (!comment) {
      throw new NotFoundException('评论不存在');
    }

    if (comment.likeCount > 0) {
      comment.likeCount -= 1;
    }
    return this.commentRepository.save(comment);
  }

  /**
   * 更新评论
   */
  async updateComment(
    userId: number,
    commentId: number,
    content: string,
  ): Promise<Comment> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId, userId },
    });

    if (!comment) {
      throw new NotFoundException('评论不存在或无权限修改');
    }

    comment.content = content;
    return this.commentRepository.save(comment);
  }

  /**
   * 获取评论详情
   */
  async getCommentDetail(commentId: number): Promise<Comment> {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
      relations: [
        'user',
        'novel',
        'chapter',
        'parent',
        'replies',
        'replies.user',
      ],
    });

    if (!comment) {
      throw new NotFoundException('评论不存在');
    }

    return comment;
  }

  /**
   * 获取评论列表
   */
  async getComments(options: any): Promise<any> {
    const {
      novelId,
      chapterId,
      page = 1,
      limit = 10,
      sortBy = 'createdAt',
      sortOrder = 'desc',
    } = options;
    const skip = (page - 1) * limit;

    const where: any = {};
    if (novelId) where.novelId = novelId;
    if (!options.parentId) where.parentId = null as any;

    const [comments, total] = await this.commentRepository.findAndCount({
      where,
      relations: ['user', 'novel'],
      order: { [sortBy]: sortOrder.toUpperCase() },
      take: limit,
      skip,
    });

    return {
      items: comments,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 清空阅读历史
   */
  async clearReadingHistory(userId: number): Promise<void> {
    await this.readingHistoryRepository.delete({ userId });
  }

  // ==================== 书架管理方法 ====================

  /**
   * 创建书架
   */
  async createBookshelf(userId: number, data: {
    name: string;
    description?: string;
    sortOrder?: number;
  }): Promise<Bookshelf> {
    // 检查同名书架是否存在
    const existingBookshelf = await this.bookshelfRepository.findOne({
      where: { userId, name: data.name, status: BookshelfStatus.ACTIVE },
    });
    if (existingBookshelf) {
      throw new BadRequestException('书架名称已存在');
    }

    const bookshelf = new Bookshelf();
    bookshelf.userId = userId;
    bookshelf.name = data.name;
    bookshelf.description = data.description;
    bookshelf.sortOrder = data.sortOrder || 0;
    bookshelf.isDefault = false;
    bookshelf.status = BookshelfStatus.ACTIVE;

    return this.bookshelfRepository.save(bookshelf);
  }

  /**
   * 获取用户书架列表
   */
  async getUserBookshelves(userId: number, options: any = {}) {
    const { page = 1, limit = 50, sortBy = 'sortOrder', sortOrder = 'asc' } = options;
    const skip = (page - 1) * limit;

    const [bookshelves, total] = await this.bookshelfRepository.findAndCount({
      where: { userId, status: BookshelfStatus.ACTIVE },
      relations: ['favorites'],
      order: { [sortBy]: sortOrder.toUpperCase() },
      take: limit,
      skip,
    });

    // 为每个书架添加收藏数量统计
    const bookshelvesWithCount = await Promise.all(
      bookshelves.map(async (bookshelf) => {
        const count = await this.favoriteRepository.count({
          where: { bookshelfId: bookshelf.id },
        });
        return {
          ...bookshelf,
          bookCount: count,
        };
      }),
    );

    return {
      items: bookshelvesWithCount,
      meta: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
        hasNext: page * limit < total,
        hasPrev: page > 1,
      },
    };
  }

  /**
   * 更新书架
   */
  async updateBookshelf(userId: number, bookshelfId: number, data: {
    name?: string;
    description?: string;
    sortOrder?: number;
  }): Promise<Bookshelf> {
    const bookshelf = await this.bookshelfRepository.findOne({
      where: { id: bookshelfId, userId, status: BookshelfStatus.ACTIVE },
    });

    if (!bookshelf) {
      throw new NotFoundException('书架不存在或无权限访问');
    }

    // 不能修改默认书架的名称
    if (bookshelf.isDefault && data.name && data.name !== bookshelf.name) {
      throw new BadRequestException('不能修改默认书架的名称');
    }

    // 如果修改了名称，检查是否重复
    if (data.name && data.name !== bookshelf.name) {
      const existingBookshelf = await this.bookshelfRepository.findOne({
        where: { userId, name: data.name, status: BookshelfStatus.ACTIVE },
      });
      if (existingBookshelf) {
        throw new BadRequestException('书架名称已存在');
      }
    }

    // 更新字段
    if (data.name !== undefined) bookshelf.name = data.name;
    if (data.description !== undefined) bookshelf.description = data.description;
    if (data.sortOrder !== undefined) bookshelf.sortOrder = data.sortOrder;

    return this.bookshelfRepository.save(bookshelf);
  }

  /**
   * 删除书架
   */
  async deleteBookshelf(userId: number, bookshelfId: number): Promise<void> {
    const bookshelf = await this.bookshelfRepository.findOne({
      where: { id: bookshelfId, userId, status: BookshelfStatus.ACTIVE },
    });

    if (!bookshelf) {
      throw new NotFoundException('书架不存在或无权限访问');
    }

    if (bookshelf.isDefault) {
      throw new BadRequestException('不能删除默认书架');
    }

    // 将该书架的收藏移到默认书架
    const defaultBookshelf = await this.bookshelfRepository.findOne({
      where: { userId, isDefault: true, status: BookshelfStatus.ACTIVE },
    });

    if (defaultBookshelf) {
      await this.favoriteRepository.update(
        { userId, bookshelfId },
        { bookshelfId: defaultBookshelf.id },
      );
    } else {
      // 如果没有默认书架，设置为null
      await this.favoriteRepository.update(
        { userId, bookshelfId },
        { bookshelfId: null },
      );
    }

    await this.bookshelfRepository.remove(bookshelf);
  }

  /**
   * 批量移动收藏到指定书架
   */
  async moveFavoritesToBookshelf(userId: number, data: {
    bookshelfId: number;
    novelIds: number[];
  }): Promise<{ success: number; failed: number }> {
    const { bookshelfId, novelIds } = data;

    // 检查书架是否存在且属于当前用户
    const bookshelf = await this.bookshelfRepository.findOne({
      where: { id: bookshelfId, userId, status: BookshelfStatus.ACTIVE },
    });
    if (!bookshelf) {
      throw new NotFoundException('书架不存在或无权限访问');
    }

    let success = 0;
    let failed = 0;

    for (const novelId of novelIds) {
      try {
        // 检查收藏记录是否存在
        const favorite = await this.favoriteRepository.findOne({
          where: { userId, novelId },
        });
        if (favorite) {
          favorite.bookshelfId = bookshelfId || null;
          await this.favoriteRepository.save(favorite);
          success++;
        } else {
          failed++;
        }
      } catch (error) {
        failed++;
      }
    }

    return { success, failed };
  }

  /**
   * 获取默认书架（如果不存在则创建）
   */
  async getOrCreateDefaultBookshelf(userId: number): Promise<Bookshelf> {
    let defaultBookshelf = await this.bookshelfRepository.findOne({
      where: { userId, isDefault: true, status: BookshelfStatus.ACTIVE },
    });

    if (!defaultBookshelf) {
      defaultBookshelf = await this.createBookshelf(userId, {
        name: '默认书架',
        description: '系统默认创建的书架',
        sortOrder: 0,
      });
      defaultBookshelf.isDefault = true;
      await this.bookshelfRepository.save(defaultBookshelf);
    }

    return defaultBookshelf;
  }
}
